const { assert } = require('koa/lib/context')
const ServerResponse = require('@root/middlewares/resHandler');
const Router = require('koa-router');
const router = Router();

const Article = require('@root/models/article.model');
const User = require('@root/models/user.model');
const Comment = require('@root/models/comment.model');


exports.getOne = async ctx => {

    const user = ctx.state.user ? await User.findById(ctx.state.user.id) : null
    ctx.body = { article: ctx.state.article.toJSONFor(user) };
}
exports.createOne = async ctx => {

    const user = await User.findById(ctx.state.user.id);

    if (!user) return (ctx.status = 404);

    const article = new Article(ctx.request.body.article);

    article.author = user;

    await article.save();

    ctx.body = ServerResponse.createBySuccessMsgAndData(
        '发布成功', {
        article: article.toJSONFor(user)
    });
}
exports.updateOne = async ctx => {

    const user = await User.findById(ctx.state.user.id);

    const { article: updateArticle } = ctx.request.body;

    let { article } = ctx.state;

    if (article.author._id.toString() === ctx.state.user.id.toString()) {
        if (typeof updateArticle.title !== 'undefined') {
            article.title = updateArticle.title;
        }

        if (typeof updateArticle.body !== 'undefined') {
            article.body = updateArticle.body;
        }

        if (typeof updateArticle.tagList !== 'undefined') {
            article.tagList = updateArticle.tagList;
        }
        await article.save();
        ctx.body = ServerResponse.createBySuccessMsgAndData(
            '修改成功',
            article.toJSONFor(user)
        );
    } else {
        ctx.body = ServerResponse.createByErrorMsg(
            '你没有权限');
    }
}
exports.deleteOne = async ctx => {
    const { user, article } = ctx.state;
    await article.remove();
    assert(ctx.boyd, 200, '删除成功')
}
exports.deleteMany = async ctx => {
    const { ids } = ctx.request.body;
    const res = await Article.deleteMany({ _id: { $in: ids } })
    ctx.body = ServerResponse.createBySuccessMsg(
        '删除成功'
    );
}
exports.favorite = async ctx => {
    let {article,user:currentUser} = ctx.state;
    const user = await User.findById(currentUser.id);

    if (!user) {
        ctx.body = ServerResponse.createBySuccessMsg('你未登录')
    }

    await user.favorite(article._id);
    await article.addFavorite(ctx.state.user.id)
    ctx.body = ServerResponse.createBySuccessMsg('收藏成功')
}

exports.unFavorite = async ctx => {
    let article = ctx.state.article;
    await article.removeFavorite(ctx.state.user.id)
    ctx.body = ServerResponse.createBySuccessMsg('取消收藏成功')
}

exports.getAll = async ctx => {
    const { limit = 20, offset = 0 } = ctx.request.body
    let query = {};

    const req = ctx.request;

    if (typeof req.query.limit !== 'undefined') {
        limit = req.query.limit;
    }

    if (typeof req.query.offset !== 'undefined') {
        offset = req.query.offset;
    }

    if (typeof req.query.tag !== 'undefined') {
        query.tagList = { $in: [req.query.tag] };
    }

    // author 用户id
    const author = req.query.author
    ? await User.findById(req.query.author)
    : null;
    if(author){
        query.author = author._id;
    }

     // favorited 文章id
     const favoriter = req.query.favorited?await User.findById(req.query.favorited):null

    if (favoriter) {
        query._id = { $in: favoriter.favorites };
    } else if (req.query.favorited) {
        query._id = { $in: [] };
    }


    const findResults = await Article.find(query)
        .limit(Number(limit))
        .skip(Number(offset))
        .sort({ createdAt: 'desc' })
        .populate('author');

    const articles = []
    for (let article of findResults) {
        const author = await User.findById(article.author)
        let following = false

        if (ctx.user) {
            following = author.assertFollower(ctx.state.user.id)
        }

        const target = {
            slug: article.slug,
            title: article.title,
            description: article.description,
            body: article.body,
            tagList: article.tagList,
            createdAt: article.createdAt,
            updatedAt: article.updatedAt,
            favorited: ctx.state.user ? article.assertFavorite(ctx.state.user.id) : false,
            favoritesCount: article.getFavoriteCount(),
            author: {
                username: author.username,
                bio: author.bio,
                image: author.image,
                following
            },
        }
        articles.push(target)
    }
    const articlesCount = await Article.count(query);

    ctx.body = {
        id:ctx.state.user,
        articles,
        articlesCount
    };
}


exports.getComments = async ctx => {
    const {user,article} = ctx.state;
    const comments = []
    const findComments = await Comment.find({ article })

    for (let _comment of findComments) {
        const author = await User.findById(_comment.author)
       
        if (user) {
           
            following = author.assertFollower(user.id)
        }

        const comment = {
            id: _comment.id,
            creatAt: _comment.creatAt,
            updateAt: _comment.updateAt,
            body: _comment.body,
            author: {
                username: author.username,
                bio: author.bio,
                image: author.image,
                following
            }
        }
        comments.push(comment)
    }
    // return ctx.body = comments
    ctx.body = ServerResponse.createBySuccessMsgAndData('获取全部评论成功',{comments})
    
}

exports.deleteComment = async ctx => {
    const comment = await Comment.findById(ctx.params.comment)
    comment.remove();
    ctx.body = ServerResponse.createBySuccessMsg('删除成功')
}

exports.addComment = async ctx=>{
    const {article,user} = ctx.state;
    const author = await User.findById(user.id)
    const newComment = new Comment({
        body: ctx.request.body.comment.body,
        article: article.id,
        author: author.id,
    })
    await newComment.save()
    const comment = {
        id: newComment.id,
        creatAt: newComment.creatAt,
        updateAt: newComment.updateAt,
        body: newComment.body,
        author: {
            username: author.username,
            ok:'hahaha',
            bio: author.bio,
            image: author.image,
            following:author.assertFollower(author.id)
        }
    }

    ctx.body = ServerResponse.createBySuccessMsgAndData('评论成功',{comment})
}
